package org.force4spring.query;

/**
 * Implementation of <code>Expression</code> to wrap value in a <code>ConditionExpression</code>.
 * This class provides appropriate handling for arrays of values and escaping for String values.
 * 
 * @author Max Rudman
 */
public class ValueExpression implements Expression {
	private Object[] values;
	
	public ValueExpression(String value) {
		assert (value != null);
		this.values = new String[]{value};
	}
	
	public ValueExpression(Number value) {
		assert (value != null);
		this.values = new Number[]{value};
	}
	
	public ValueExpression(Boolean value) {
		assert (value != null);
		this.values = new Boolean[]{value};
	}
	
	public ValueExpression(String[] values) {
		assert (values != null);
		assert (values.length > 0);
		this.values = values;
	}
	
	public ValueExpression(Number[] values) {
		assert (values != null);
		assert (values.length > 0);
		this.values = values;
	}
	
	protected String escape(String in) {
		in = in.replaceAll("'", "\'");
		return in;
	}

	/**
	 * @see org.force4spring.query.Expression#buildSOQL()
	 */
	public String buildSOQL() {
		StringBuffer soql = new StringBuffer();
		for (int i=0;i<values.length;i++) {
			if (i > 0) {
				soql.append(",");
			}
			if (values[i] instanceof String) {
				soql.append("'").append(escape((String)values[i])).append("'");
			} else {
				soql.append(values[i]);
			}
		}
		return soql.toString();
	}
}
